package com.air.ma.philosopher;

import lombok.SneakyThrows;

/**
 * 哲学家
 *
 * @author shent
 */
public class Philosopher extends Thread {

    private ChopStick left, right;
    private int index;

    public Philosopher(String name, int index, ChopStick left, ChopStick right) {
        this.setName(name);
        this.left = left;
        this.right = right;
        this.index = index;
    }


    @SneakyThrows
    @Override
    public void run() {
        //奇数和偶数的哲学家 起手左右不同，可以解决死锁问题
        if (index % 2 == 0) {
            synchronized (right) {
                Thread.sleep(1000 + index * 1000);
                synchronized (left) {
                    Thread.sleep(1000);
                    System.out.println(index + "号 哲学家已经吃完");
                }
            }
        } else {
            synchronized (left) {
                Thread.sleep(1000 + index * 1000);
                synchronized (right) {
                    Thread.sleep(1000);
                    System.out.println(index + "号 哲学家已经吃完");
                }
            }
        }

    }
}
